<template>
  <el-card class="swiper-container">
    <template #header>
      <div class="header">
        <div class="search">
          <el-input v-model="keywords" placeholder="搜索昵称"
            @change="query"
            @enter="query"
            clearable
            :style="{
            width: '220px'
          }">
            <template #prepend>
              <el-select v-model="state.prepend" style="width: 90px;">
                <el-option label="昵称" value="nickname"/>
                <el-option label="手机号" value="phone"/>
              </el-select>
            </template>
          </el-input>

          <el-select class="ml-10" placeholder="性别" v-model="params.gender"
            @change="getList()">
            <template #prefix>
              <div class="pl-10px">性别：</div>
            </template>
            <el-option v-for="item in [
                {value: -1, label: '全部'},
                {value: 0, label: '保密'},
                {value: 1, label: '男性'},
                {value: 2, label: '女性'}
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>

          <el-select class="ml-10" placeholder="状态" v-model="params.status"
            @change="getList()">
            <template #prefix>
              <div class="pl-10px">状态：</div>
            </template>
            <el-option v-for="item in [
                {value: 0, label: '全部'},
                {value: 1, label: '正常'},
                {value: 2, label: '冻结'}
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </div>
        <el-button-group>
          <el-button type="primary" @click="rider">设为骑手</el-button>
          <el-button type="success" @click="solve">解除冻结</el-button>
          <el-button type="warning" @click="forbid">冻结账户</el-button>
          <el-popconfirm title="确定删除吗？"
            cancel-button-text="否"
            confirm-button-text="是"
            @confirm="deleted">
            <template #reference>
              <el-button type="danger">批量删除
              </el-button>
            </template>
          </el-popconfirm>
        </el-button-group>
      </div>
    </template>
    <el-table class="table-row-optimize"
      v-loading="state.loading" tooltip-effect="dark"
      ref="multipleTable" :data="state.tableData"
      style="width: 100%" @selection-change="selectionChangeIds">
      <el-table-column type="selection" width="40"/>
      <el-table-column v-viewer label="" align="center" width="80">
        <template #default="scope">
          <div class="user-avatar">
            <img class="img-banner"
              :src="scope.row.avatar"
              @click="preview(scope.row)" :alt="scope.row.nickname"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="会员 / 昵称">
        <template #default="scope">
          <div class="user-nickname">
            <!-- VIP等级 -->
            <el-tag v-if="scope.row.level === 2" :style="{
              backgroundColor: '#FFA963',
              borderColor: '#FFA963',
              color: '#FFFFFF'
            }">铂金
            </el-tag>
            <el-tag v-if="scope.row.level === 1" type="warning">黄金</el-tag>
            <el-tag v-if="scope.row.level === 0" type="info">普通</el-tag>

            <span class="nickname" v-if="scope.row.gender === 1"
              style="color: #419cfc;">{{ scope.row.nickname }}</span>
            <span class="nickname" v-if="scope.row.gender === 2"
              style="color: #e45a94;">{{ scope.row.nickname }}</span>
            <span class="nickname" v-if="scope.row.gender === 0">{{ scope.row.nickname }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" align="center" width="140"/>
      <el-table-column prop="integral" label="我的金额" align="center" width="100">
        <template #default="scope">
          <span class="user-number">{{ parseFloat(scope.row.balance) }}</span>
          <span class="user-units">元</span>
        </template>
      </el-table-column>
      <el-table-column prop="integral" label="可提现余额" align="center" width="100">
        <template #default="scope">
          <span class="user-number">{{ parseFloat(scope.row.withdraw) }}</span>
          <span class="user-units">元</span>
        </template>
      </el-table-column>

      <el-table-column label="福卡" align="center" width="70">
        <template #default="scope">
          <span class="user-number">{{ scope.row.foka_number }}</span>
          <span class="user-units">张</span>
        </template>
      </el-table-column>
      <el-table-column prop="integral" label="积分" align="center" width="90">
        <template #default="scope">
          <span class="user-number">{{ scope.row.integral }}</span>
          <span class="user-units">积分</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="70">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 2" type="warning">冻结</el-tag>
          <el-tag v-else type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" width="110">
        <template #default="scope">
          {{ toDateTime(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" max-width="120">
        <template #default="scope">
          <el-button-group>
            <el-button type="primary" @click="detail(scope.row)">详情</el-button>

            <!-- 已储值的用户，不能继续储值操作 -->
            <el-popconfirm v-if="scope.row.level !== 2"
              width="220"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确认该用户已储值2万元？"
              @confirm="stored(scope.row)">
              <template #reference>
                <el-button color="#ff9800" style="color: #fff;">储值</el-button>
              </template>
            </el-popconfirm>

            <el-popconfirm width="220"
              cancel-button-text="取消"
              confirm-button-text="确定"
              title="确定要删除该用户吗？"
              :icon="InfoFilled"
              icon-color="#626AEF"
              @confirm="deleted(scope.row)">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!--总数超过一页，再展示分页器-->
    <el-pagination
      background
      layout="prev, pager, next, total"
      :total="state.total"
      :page-size="params.limit"
      :current-page="params.page"
      @current-change="changePage"
    />
  </el-card>

  <user-detail ref="refDetail"/>

  <!-- Image Preview -->
  <viewer :images="images">
    <img v-for="src in images" :key="src" :src="src">
  </viewer>
</template>

<script setup>
import { InfoFilled } from '@element-plus/icons-vue'
import { toDateTime } from "../utils";
import { ElMessage } from "element-plus";
import UserDetail from "./user/detail.vue";
import { getCurrentInstance, onMounted, reactive, ref, watch } from "vue";
import {
  AdminUserBindriderPost,
  AdminUserDel,
  AdminUserList,
  AdminUserPostOnlyStatus,
  AdminUserStoredPost
} from "../api/server/user";

const { proxy } = getCurrentInstance()
const images = ref([])
const refDetail = ref(null)
const state = reactive({
  loading: false,
  prepend: 'nickname',
  tableData: [], // 数据列表
  checkedIds: [], // 选中项
  total: 0 // 总条数
});

const getCheckedIds = () => {
  return state.checkedIds.length ? state.checkedIds.map(d => d.id) : []
}

const keywords = ref('')
const params = reactive({
  page: 1,
  limit: 10,
  gender: -1,
  status: 0
})

onMounted(() => {
  getList()
})

watch(() => state.prepend, (value, oldest) => {
  if (keywords.value) {
    delete params[oldest]
    params[value] = keywords.value
    getList()
  }
})
watch(keywords, (value, oldest) => {
  params[state.prepend] = value
  getList()
})

const query = () => {
  params[state.prepend] = keywords.value
  getList()
}

const getList = async () => {
  state.loading = true;
  const { data, total, current_page } = await AdminUserList(params)
  state.tableData = data
  state.total = total
  params.page = current_page
  state.loading = false;
}

const stored = async (row) => {
  const { code } = await AdminUserStoredPost(row.id)
  if (code === 200) {
    ElMessage.success('储值代金券发放成功')
  } else {
    ElMessage.error('储值代金券发放失败')
  }
  await getList()
}

const selectionChangeIds = row => state.checkedIds = row
const preview = (row) => proxy.$viewerApi({ images: [row.avatar] })
const detail = row => refDetail.value.show(row.id)

const deleted = async row => {
  const ids = row.hasOwnProperty('id') ? [row.id] : getCheckedIds()
  if (ids.length === 0) {
    ElMessage.error('请选择删除项')
    return false
  }
  await AdminUserDel(ids.toString()) && await getList()
}

const rider = async () => {
  let ids = getCheckedIds()
  if (ids.length === 0) return false

  const { code, msg } = await AdminUserBindriderPost({ ids })
  if (code === 200) {
    ElMessage.success('操作成功')
  } else {
    ElMessage.error(msg)
  }

}

const solve = async () => {
  let ids = getCheckedIds()
  if (ids.length === 0) {
    ElMessage.warning('请勾选数据')
    return
  }

  await AdminUserPostOnlyStatus({ id: ids, status: 1 })
  ElMessage.success('操作成功')
  await getList()
}

const forbid = async () => {
  let ids = getCheckedIds()
  if (ids.length === 0) {
    ElMessage.warning('请勾选数据')
    return
  }
  await AdminUserPostOnlyStatus({ id: ids, status: 2 })
  ElMessage.success('操作成功')
  await getList()
}

const changePage = (page) => {
  params.page = page
  getList()
}

</script>

<style scoped>

.swiper-container {
  min-height: 100%;
}

.ml-10 {
  margin-left: 10px;
  width: 140px;
}

:deep(.el-card.is-always-shadow) {
  min-height: 100%;
}

img.img-banner {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  border: 1px dotted rgb(64 158 255 / 33%);
  object-fit: cover;
  cursor: pointer;
}

.user-avatar {
  position: relative;
}

.user-nickname {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.user-nickname .nickname {
  margin-left: 10px;
}

.user-number {
  font-size: 15px;
  color: #ffa502;
}

.user-units {
  font-size: 8px;
  color: rgb(0 0 0 / 30%);
}

</style>
